package com.gzsxy.esjy.message.bus;


import com.gzsxy.esjy.bus.event.InnerProtocolMessageEvent;
import com.gzsxy.esjy.bus.message.InnerProtocol;
import com.gzsxy.esjy.bus.subscrib.DefaultStream;
import com.gzsxy.esjy.message.dispatch.MessageDispatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 事件监听
 * @author zhangxiaolong
 *
 */
@Component
@Slf4j
public class BusEventListener {

	private static final String PRE_FIX = "/" ;
	
	@Autowired
	private MessageDispatch messageDispatch ;
	
	/**
	 * 监听从bus的消息传输到websocket
	 */
	@EventListener(InnerProtocolMessageEvent.class)
	public void event(InnerProtocolMessageEvent event) {
		InnerProtocol message = event.getMessage();
		Map<String, Object> headers = event.getMap();
		String dest = (String) headers.get(DefaultStream.HEADER_NAME);
		String cmd = message.getCmd();
		if(!cmd.startsWith(PRE_FIX)) {
			cmd +=PRE_FIX ;
		}
		log.info("接收到来自{}的消息 cmd=【{}】",dest,cmd);
//		message.setCmd(dest.toLowerCase()+cmd);
		try {
			messageDispatch.busToWebSocket(message,dest);
		} catch (Exception e) {
			log.error("event 消息推送失败",e);
		}
	}



}
